#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

void test0(){
    int * p = (int*)malloc(sizeof(int));
    *p = 100;
    cout << *p << endl;
    free(p);
    p = nullptr;

    //在堆上申请int型数据的空间，
    //并将该空间上的数据初始化为4
    int * p1 = new int(4);
    cout << *p1 << endl;
    delete p1;
    p1 = nullptr;
    /* free(p1); */


    //初始化为该类型的默认值
    int * p2 = new int();
    cout << *p2 << endl;
    delete p2;
    p2 = nullptr;

    //不推荐这样写，因为可能无法确保完成了初始化
    /* int * p4 = new int; */
    /* cout << *p4 << endl; */

    char * p3 = new char();
    cout << *p3 << endl;
    delete p3;
    p3 = nullptr;
    
}

void test1(){
    /* int * p = new int[10](); */
    int * p = new int[10]{1,2,3,4,5,6};
    for(int idx = 0; idx < 10; ++idx){
        cout << p[idx] << " ";
    }
    cout << endl;
    cout << p << endl;
    delete [] p;
    p = nullptr;
}

void test2(){
    char * p = new char[11]();
    for(int idx = 0; idx < 10; ++idx){
        p[idx] = 'a' + idx;
    }

    for(int idx = 0; idx < 10; ++idx){
        cout << p[idx] << " ";
    }
    cout << endl;
    delete [] p;
    p = nullptr;

    //如果使用大括号，在大括号中应该写上char型数据
    /* char * p2 = new char[10]{"hello"}; */
    char * p2 = new char[10]{'h','e','l','l','o'};
    for(int idx = 0; idx < 10; ++idx){
        cout << p2[idx] << " ";
    }
    cout << endl;
    delete [] p2;
    p2 = nullptr;

    //在C++中使用如下方式代表C风格字符串
    const char * pstr = "hello,world!!!";
    /* pstr[0] = 'H'; */


    cout << strlen(pstr) << endl;
    cout << sizeof(pstr) << endl;

    /* char * p3 = new char[6](); */
    char * p3 = new char[strlen(pstr) + 1]();
    strcpy(p3,pstr);

    //这种读取内容的方式比较麻烦
    for(size_t idx = 0; idx < strlen(pstr) + 1; ++idx){
        cout << p3[idx] << " ";
    }
    cout << endl;

    //输出流运算符对char型指针有默认重载效果
    //会自动访问这个指针指向的内容
    cout << p3 << endl;
    delete [] p3;
    p3 = nullptr;
}

int main(void){
    test2();
    return 0;
}
